import React, { useState } from "react";
import { Menu } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
export default function index() {
  const items: MenuItem[] = [
    {
      label: "栏目 1",
      key: "/page1",
      icon: <PieChartOutlined />,
    },
    {
      label: "栏目 2",
      key: "/page2",
      icon: <DesktopOutlined />,
    },
    {
      label: "栏目 3",
      key: "page3",
      icon: <UserOutlined />,
      children: [
        {
          label: "栏目 301",
          key: "/page3/page301",
        },
        {
          label: "栏目 302",
          key: "/page3/page302",
        },
        {
          label: "栏目 303",
          key: "/page3/page303",
        },
      ],
    },
    {
      label: "栏目 4",
      key: "page4",
      icon: <TeamOutlined />,
      children: [
        {
          label: "Team 1",
          key: "/page4/page401",
        },
        {
          label: "Team 2",
          key: "/page4/page402",
        },
      ],
    },
    {
      label: "栏目 5",
      key: "page5",
      icon: <FileOutlined />,
    },
  ];
  const navigateTo = useNavigate();
  const menuClick = (e: { key: string }) => {
    navigateTo(e.key);
  };
  // openKeys 当前所有展开着的数组，一开始给空默认不展示

  const hdOpenChange = (keys: string[]) => {
    // 点击展开和收缩的时候执行这里的代码
    // console.log(keys); // 这些展开这的keys的数组
    // 设置为最后一项
    setOpenKeys([keys[keys.length - 1]]);
  };

  const location = useLocation().pathname;
  let firstOpenKey: string = "";
  function findKey(obj: { key: string }) {
    return obj.key === location;
  }
  // 多对比的是多个children
  for (let i = 0; i < items.length; i++) {
    // 判断找到不到
    if (
      items[i]!["children"] &&
      items[i]!["children"].length > 0 &&
      items[i]!["children"].find(findKey)
    ) {
      firstOpenKey = items[i]!.key as string;
      break;
    }
  }
  const [openKeys, setOpenKeys] = useState([firstOpenKey]);
  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={[location]}
      mode="inline"
      items={items}
      onClick={menuClick}
      // 补充这1个属性 和1个事件：
      // openKeys 表示当前所有展开着的数组
      openKeys={openKeys}
      // 点击展开和收缩的时候执行这里的代码
      onOpenChange={hdOpenChange}
    />
  );
}
